<template>
  <div class="app-container home">
    <div class="data-statistics">

      <div class="section-title-section" v-if="canSelectDept">
        <div></div>
        <h2 class="section-title">分局新闻可视化展示</h2>
        <div class="week-selection">
          <el-date-picker
            v-model="dateRangeValue"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </div>

      <div class="section-container" v-if="canSelectDept">
        <!-- 柱状图容器 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3>部门文章数量统计</h3>
          </div>
          <div class="chart-wrapper">
            <div id="barChart" class="chart"></div>
          </div>
        </div>
        <!-- 饼图容器 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3>部门文章比例分析</h3>
          </div>
          <div class="chart-wrapper">
            <div id="pieChart" class="chart"></div>
          </div>
        </div>
      </div>

      <div class="section-title-section">
        <div></div>
        <h2 class="section-title">文章栏目计数可视化展示</h2>
        <div class="week-selection">
          <el-select v-if="canSelectDept" v-model="selectedDept" placeholder="请选择分局" clearable @change="onDeptChange" style="width: 200px; margin-right: 20px;">
            <el-option
              v-for="item in deptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select
            v-model="selectedColumns"
            multiple
            filterable
            clearable
            collapse-tags
            placeholder="请选择栏目显示"
            @change="onColumnChange"
            style="width: 200px; margin-right: 20px;">
            <el-option
              v-for="column in allColumns"
              :key="column.name"
              :label="column.name"
              :value="column.name">
            </el-option>
          </el-select>
          <el-button
            v-if="allColumns && allColumns.length > 0"
            @click="toggleSelectAllColumns"
            size="small"
            style="margin-right: 10px;">
            {{ selectedColumns.length === allColumns.length ? '取消全选' : '全选' }}
          </el-button>
          <el-button
            v-if="selectedColumns && selectedColumns.length > 0"
            @click="resetColumnFilter"
            size="small"
            style="margin-right: 20px;">
            重置筛选
          </el-button>
          <el-date-picker
            v-model="dateRangeValue2"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </div>

      <div class="section-container">
        <!-- 柱状图容器 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3>栏目文章数量统计</h3>
          </div>
          <div class="chart-wrapper">
            <div id="barChart2" class="chart"></div>
          </div>
        </div>
        <!-- 饼图容器 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3>栏目文章数量比例</h3>
          </div>
          <div class="chart-wrapper">
            <div id="pieChart2" class="chart"></div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {getGraph1, getGraph1ByDept, getGraph2, getDeptList, getUserPermission} from '@/api/dashboard/index'
import {listConlumnList} from '@/api/conlumn/conlumn'
import {formatDate, formatTime} from "@/utils";
import request from '@/utils/request'

export default {
  name: 'DataStatistics',
  data() {
    return {
      dateRangeValue: [],
      dateRangeValue2: [],
      selectedDept: '', // 选中的分局
      deptOptions: [], // 分局选项
      canSelectDept: false, // 是否可以选分局
      userDept: '', // 用户所属部门
      userDeptOrigin: '', // 用户所属的分局名称
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择大于等于今天的日期，即只能选今天以前
          return time.getTime() >= new Date(new Date().toLocaleDateString()).getTime()
        }
      },

      pieChart: null,
      barChart: null,
      // 栏目筛选相关数据
      selectedColumns: [], // 选中的栏目
      allColumns: [], // 所有栏目列表
      chartData: {
        pie: {
          title: '部门文章比例分析',
          seriesName: '文章数量',
          data: []
        },
        bar: {
          title: '部门文章数量统计',
          xAxisName: '部门',
          yAxisName: '文章数量',
          xAxisData: [],
          seriesData: []
        }
      },
      chartData2: {
        pie: {
          title: '各栏目文章数量比例',
          seriesName: '文章数量',
          data: []
        },
        bar: {
          title: '栏目文章数量统计',
          xAxisName: '栏目',
          yAxisName: '文章数量',
          xAxisData: [],
          seriesData: []
        }
      }
    }
  },
  watch: {
    dateRangeValue() {
      this.fetchData()
    },
    dateRangeValue2() {
      this.fetchData()
    }
  },
  mounted() {
    // 设置默认日期范围为本年到今天
    const now = new Date()
    const startOfYear = new Date(now.getFullYear(), 0, 1) // 本年第一天
    const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()) // 今天

    this.dateRangeValue = [startOfYear, endOfDay]
    this.dateRangeValue2 = [startOfYear, endOfDay]

    // 获取用户信息和分局列表
    this.fetchUserInfo()
    this.fetchDeptList()
    // 获取所有栏目列表
    this.fetchAllColumns()

    // 页面加载时调用一次查询，使用默认的本年到今天日期范围
    this.fetchData()
  },
  methods: {
    // 获取用户信息和权限
    async fetchUserInfo() {
      try {
        // 获取当前用户权限信息
        const permissionRes = await getUserPermission()

        if (permissionRes && permissionRes.data) {
          this.canSelectDept = permissionRes.data.canSelectDept
          this.userDept = permissionRes.data.userDept
          this.userDeptOrigin = permissionRes.data.userDeptOrigin  // 用户所属的分局名称

          // 如果是直接隶属于荆州市长江河道管理局的部门用户，设置默认选中的部门为所属的分局
          if (!this.canSelectDept && this.userDeptOrigin) {
            this.selectedDept = this.userDeptOrigin
          }
          // 如果是市局用户且可以选分局，但没有默认选中任何分局，则不设置默认值
          // 让后端根据用户身份自动查询其部门及其子部门的数据
        }
      } catch (error) {
        console.error('获取用户权限信息失败:', error)
      }
    },

    // 获取所有栏目列表
    async fetchAllColumns() {
      try {
        const res = await listConlumnList()
        if (res && res.rows) {
          this.allColumns = res.rows.map(item => ({
            name: item.name || item.columnName || item
          }))
        }
      } catch (error) {
        console.error('获取栏目列表失败:', error)
      }
    },

    // 检查是否为市局子部门
    async checkIfCityBureauSubordinate() {
      try {
        // 这里可以调用后端接口检查用户是否为市局子部门
        // 暂时返回false，后续可以根据实际需求实现
        return false
      } catch (error) {
        console.error('检查市局子部门失败:', error)
        return false
      }
    },

    // 获取分局列表
    async fetchDeptList() {
      try {
        const res = await getDeptList()
        this.deptOptions = res.data
      } catch (error) {
        console.error('获取分局列表失败:', error)
      }
    },

    // 从数据中提取栏目列表（不覆盖已有的完整栏目列表）
    extractColumnsFromData(data) {
      // 不再覆盖allColumns，保持从API获取的完整栏目列表
      // 这个方法可以用于其他目的，但现在我们不需要它修改allColumns
      return;
    },
    // 分局选择变化时的处理
    onDeptChange() {
      // 重置栏目筛选
      this.selectedColumns = []
      // 重新获取数据
      this.fetchData()
    },

    // 栏目选择变化时的处理
    onColumnChange() {
      // 重新获取数据
      this.fetchData()
    },

    // 全选/取消全选栏目
    toggleSelectAllColumns() {
      if (this.selectedColumns.length === this.allColumns.length) {
        // 如果已经全选，则取消全选
        this.selectedColumns = []
      } else {
        // 如果没有全选，则全选所有栏目
        this.selectedColumns = this.allColumns.map(column => column.name)
      }
      // 重新获取数据
      this.fetchData()
    },

    // 重置栏目筛选
    resetColumnFilter() {
      this.selectedColumns = []
      // 重新获取数据
      this.fetchData()
    },

    // 获取数据
    async fetchData() {
      const [startDate, endDate] = this.dateRangeValue
      const [startDate2, endDate2] = this.dateRangeValue2

      // 获取按部门统计的图表数据
      let res = await getGraph1ByDept(formatDate(startDate), formatDate(endDate))
      // 第二个图表支持传递分局参数
      let res2 = await getGraph2(formatDate(startDate2), formatDate(endDate2), this.selectedDept)
      const {rows: mockData} = res
      const {rows: mockData2} = res2

      this.formatData(mockData)
      this.formatData2(mockData2)

      this.initCharts()
    },
    // 格式化数据
    formatData(data) {
      const pieData = []
      const barXAxisData = []
      const barSeriesData = []

      data.forEach(item => {
        pieData.push({
          name: item.deptName,
          value: item.count
        })
        barXAxisData.push(item.deptName)
        barSeriesData.push(item.count)
      })

      this.chartData.pie.data = pieData
      this.chartData.bar.xAxisData = barXAxisData
      this.chartData.bar.seriesData = barSeriesData
    },
    // 格式化数据
    formatData2(data) {
      const pieData = []
      const barXAxisData = []
      const barSeriesData = []

      // 默认显示所有数据，如果有选中的栏目，则只显示选中的栏目数据
      let filteredData = data || [];
      if (this.selectedColumns && this.selectedColumns.length > 0) {
        filteredData = data.filter(item => this.selectedColumns.includes(item.columnName));
      }

      filteredData.forEach(item => {
        pieData.push({
          name: item.columnName,
          value: item.count
        })
        barXAxisData.push(item.columnName)
        barSeriesData.push(item.count)
      })

      this.chartData2.pie.data = pieData
      this.chartData2.bar.xAxisData = barXAxisData
      this.chartData2.bar.seriesData = barSeriesData

      // 根据选择的分局更新图表标题
      if (this.selectedDept) {
        this.chartData2.pie.title = this.selectedDept + '各栏目文章数量比例'
        this.chartData2.bar.title = this.selectedDept + '栏目文章数量统计'
      } else if (this.canSelectDept) {
        // 市局用户或admin用户未选择分局时显示默认标题
        this.chartData2.pie.title = '各栏目文章数量比例'
        this.chartData2.bar.title = '栏目文章数量统计'
      } else {
        // 分局用户显示默认标题
        this.chartData2.pie.title = '各栏目文章数量比例'
        this.chartData2.bar.title = '栏目文章数量统计'
      }

      // 如果有选中的栏目，在标题中显示筛选信息
      if (this.selectedColumns && this.selectedColumns.length > 0) {
        const selectedCount = this.selectedColumns.length;
        this.chartData2.pie.title += ` (已筛选${selectedCount}个栏目)`;
        this.chartData2.bar.title += ` (已筛选${selectedCount}个栏目)`;
      }
    },
    // 初始化图表
    initCharts() {
      this.initPieChart()
      this.initBarChart()

      this.initPieChart2()
      this.initBarChart2()
    }
    ,
    // 初始化饼图
    initPieChart() {
      const pieChartElement = document.getElementById('pieChart');
      if (pieChartElement) {
        this.pieChart = echarts.init(pieChartElement);
        this.pieChart.setOption({
          title: {
            text: this.chartData.pie.title,
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: this.chartData.pie.seriesName,
              type: 'pie',
              radius: '50%',
              data: this.chartData.pie.data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    initPieChart2() {
      const pieChart2Element = document.getElementById('pieChart2');
      if (pieChart2Element) {
        this.pieChart2 = echarts.init(pieChart2Element);
        this.pieChart2.setOption({
          title: {
            text: this.chartData2.pie.title,
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: this.chartData2.pie.seriesName,
              type: 'pie',
              radius: '50%',
              data: this.chartData2.pie.data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    // 初始化柱状图
    initBarChart() {
      const barChartElement = document.getElementById('barChart');
      if (barChartElement) {
        this.barChart = echarts.init(barChartElement);
        this.barChart.setOption({
          title: {
            text: this.chartData.bar.title,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: this.chartData.bar.xAxisData,
            name: this.chartData.bar.xAxisName,
            axisLabel: {
              interval: 0,  // 显示所有标签
              formatter: function(value) {
                // 将字符串按字符分割，用换行符连接，实现垂直排列
                return value.split('').join('\n');
              },
              textStyle: {
                fontSize: 10,
                lineHeight: 12  // 设置行高，控制字符间距
              }
            }
          },
          yAxis: {
            type: 'value',
            name: this.chartData.bar.yAxisName,
            minInterval: 1
          },
          series: [
            {
              data: this.chartData.bar.seriesData,
              type: 'bar',
              label: {
                show: true,
                position: 'top',
                formatter: '{c}',
                color: '#666',
                fontSize: 12,
                fontWeight: 'bold'
              }
            }
          ]
        });
      }
    } ,
    // 初始化柱状图
    initBarChart2() {
      const barChart2Element = document.getElementById('barChart2');
      if (barChart2Element) {
        this.barChart2 = echarts.init(barChart2Element);
        this.barChart2.setOption({
          title: {
            text: this.chartData2.bar.title,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: this.chartData2.bar.xAxisData,
            name: this.chartData2.bar.xAxisName,
            axisLabel: {
              interval: 0,  // 显示所有标签
              formatter: function(value) {
                // 将字符串按字符分割，用换行符连接，实现垂直排列
                return value.split('').join('\n');
              },
              textStyle: {
                fontSize: 12,
                lineHeight: 14  // 设置行高，控制字符间距
              }
            }
          },
          yAxis: {
            type: 'value',
            name: this.chartData2.bar.yAxisName,
            minInterval: 1
          },
          series: [
            {
              data: this.chartData2.bar.seriesData,
              type: 'bar',
              label: {
                show: true,
                position: 'top',
                formatter: '{c}',
                color: '#666',
                fontSize: 12,
                fontWeight: 'bold'
              }
            }
          ]
        });
      }
    },
  },


  beforeDestroy() {
    // 销毁图表实例
    if (this.pieChart) {
      this.pieChart.dispose()
    }
    if (this.barChart) {
      this.barChart.dispose()
    }

    if (this.pieChart2) {
      this.pieChart2.dispose()
    }
    if (this.barChart2) {
      this.barChart2.dispose()
    }
  }
}
</script>

<style scoped lang="scss">
.data-statistics {
  padding: 20px;
  display: flex;
  gap: 5%;
  flex-flow: column nowrap;

  .section-title-section {
    width: 100%;
    height: 2em;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: distribute;
    justify-content: space-around;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    margin-bottom: 1.5em;
  }

  .section-container {
    display: flex;
    justify-content: space-around;
    gap: 2.5%;
  }

  .chart-container {
    margin-bottom: 30px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    flex: 1;

    .chart-header {
      padding: 15px 20px;
      border-bottom: 1px solid #f0f0f0;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .chart-wrapper {
      padding: 20px;
    }

    .chart {
      width: 100%;
      height: 400px;
    }
  }

  // 筛选按钮样式
  ::v-deep .el-button {
    &.el-button--small {
      padding: 8px 12px;
      font-size: 12px;
    }
  }
}
</style>

